package com.runner.android;

import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.games.Games;
import com.google.android.gms.plus.Plus;
import com.google.example.games.basegameutils.GameHelper;
import com.runner.RedRunner;
import com.runner.services.GameServiceInterface;
import com.runner.services.GoogleServices;

public class AndroidLauncher extends AndroidApplication implements GameServiceInterface, GameHelper.GameHelperListener {

	protected GameHelper mHelper;
	protected AdView adView;
	protected InterstitialAd adViewInter;
	private GoogleServices services;
	private RelativeLayout layout;
	private RedRunner runner;
	final static int ACHIEVEMENT_REQUEST = 6;
	final static int REQUEST_LEADERBOARD = 7;
	final static int RC_SIGN_IN = 1;
	final static int SIGN_OUT = 3;
	final static int SIGN_IN = 4;

	public AndroidLauncher() {

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Create the layout
		layout = new RelativeLayout(this);
		mHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
		mHelper.enableDebugLog(true);

		// Do the stuff that initialize() would do for you
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		mHelper.setup(this);
		mHelper.setConnectOnStart(false);
		services = new GoogleServices();
		// Create the libgdx View
		AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
		runner=new RedRunner(this, services);
		View gameView = initializeForView(runner, cfg);

		// Create and setup the AdMob view
		adView = new AdView(this); // Put in your secret key here
		adView.setAdUnitId("ca-app-pub-5099396459191162/3310196931");
		adView.setAdSize(AdSize.SMART_BANNER);

		adView.loadAd(new AdRequest.Builder().build());

		adViewInter = new InterstitialAd(this);
		adViewInter.setAdUnitId("ca-app-pub-5099396459191162/6883955333");
		adViewInter.setAdListener(new AdListener() {
			@Override
			public void onAdClosed(){
				adViewInter.loadAd(new AdRequest.Builder().build());
				runner.adClosed();
			}
		});
		adViewInter.loadAd(new AdRequest.Builder().build());

		// Add the libgdx view
		layout.addView(gameView);

		// Add the AdMob view
		RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		adParams.addRule(RelativeLayout.CENTER_IN_PARENT);

		layout.addView(adView, adParams);
		// Hook it all up
		setContentView(layout);

	}

	@Override
	public void onStart() {
		super.onStart();
		mHelper.onStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		mHelper.onStop();
	}

	@Override
	public void onActivityResult(int request, int response, Intent data) {
		super.onActivityResult(request, response, data);
		mHelper.onActivityResult(request, response, data);
		if (request == RC_SIGN_IN) {
			if (response != RESULT_OK) {
				services.setmSignedInClicked(false);
			}

			services.setmIntentInProgress(false);

			if (!mHelper.getApiClient().isConnecting()) {
				mHelper.getApiClient().connect();
			}
		} else if (request == ACHIEVEMENT_REQUEST) {

		}
	}

	@Override
	public void showAchievements() {
		if (isSignedIn()) {
			startActivityForResult(Games.Achievements.getAchievementsIntent(mHelper.getApiClient()), ACHIEVEMENT_REQUEST);
		} else {
			final AndroidLauncher temp = this;
			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(temp, "Must be signed in!", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	@Override
	public void showScores() {
		if (isSignedIn()) {
			startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mHelper.getApiClient()), REQUEST_LEADERBOARD);
		} else {
			final AndroidLauncher temp = this;
			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(temp, "Must be signed in!", Toast.LENGTH_SHORT).show();
				}
			});
		}
	}

	@Override
	public boolean isSignedIn() {
		return mHelper.isSignedIn();
	}

	@Override
	public void logOut() {
		final AndroidLauncher temp = this;
		try {
			runOnUiThread(new Runnable() {
				// @Override
				public void run() {
					mHelper.signOut();
					services.switchSignInText(false);
					services.setSignedIn(false);
					Toast.makeText(temp, "You are signed out of Google", Toast.LENGTH_SHORT).show();
				}
			});

		} catch (final Exception ex) {

		}
	}

	@Override
	public void logIn() {
		try {
			runOnUiThread(new Runnable() {
				// @Override
				public void run() {
					mHelper.beginUserInitiatedSignIn();
				}
			});
		} catch (final Exception ex) {

		}
	}

	// A helper method to resolve the current ConnectionResult error.
	private void resolveSignInError() {
		if (mHelper.mConnectionResult.hasResolution()) {
			try {
				services.setmIntentInProgress(true);
				startIntentSenderForResult(mHelper.mConnectionResult.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
			} catch (SendIntentException e) {
				// The intent was canceled before it was sent. Return to the
				// default
				// state and attempt to connect to get an updated
				// ConnectionResult.
				services.setmIntentInProgress(false);
				mHelper.getApiClient().connect();
			}
		}
	}

	public void onConnectionFailed(ConnectionResult result) {

		if (result != null) {
			if (!services.ismIntentInProgress()) {
				// Store the ConnectionResult so that we can use it later when
				// the
				// user clicks
				// 'sign-in'.
				mHelper.mConnectionResult = result;
				if (services.ismSignedInClicked()) {
					// The user has already clicked 'sign-in' so we attempt to
					// resolve all
					// errors until the user is signed in, or they cancel.
					resolveSignInError();
				}
			}
		}
	}

	@Override
	public void submitScore(int score, String LB_ID) {
		if (mHelper.isSignedIn()) {
			Games.Leaderboards.submitScore(mHelper.getApiClient(), LB_ID, (long) score);
		}
	}

	@Override
	public void onClick(int code) {
		if (code == SIGN_OUT) {
			if (mHelper.getApiClient().isConnected()) {
				services.setmSignedInClicked(false);
				Plus.AccountApi.clearDefaultAccount(mHelper.getApiClient());
				mHelper.getApiClient().disconnect();
			}
		} else if (code == SIGN_IN) {
			if (!mHelper.getApiClient().isConnecting()) {
				services.setmSignedInClicked(true);
				resolveSignInError();
			}
		}
	}

	@Override
	public void onSignInFailed() {
		services.switchSignInText(false);
		services.setSignedIn(false);
		onConnectionFailed(mHelper.mConnectionResult);
	}

	@Override
	public void onSignInSucceeded() {
		services.setmSignedInClicked(true);
		services.switchSignInText(true);
		services.setSignedIn(true);
		services.pushAccomplishments();
		Toast.makeText(this, "You are signed in to Google", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void unlockAchievements(String achievementID) {
		if (mHelper.isSignedIn()) {
			Games.Achievements.unlock(mHelper.getApiClient(), achievementID);
		} else {

		}
	}

	private void hideAd() {
		if (adView.getVisibility() == AdView.VISIBLE) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					adView.setVisibility(AdView.GONE);
					layout.removeView(adView);
				}
			});

		}

	}

	private void showAd(final LayoutParams lp) {
		if (adView.getVisibility() != AdView.VISIBLE) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					adView.setVisibility(AdView.VISIBLE);
					layout.addView(adView, lp);
				}
			});

		}

	}

	// Invoke displayInterstitial() when you are ready to display an
	// interstitial.
	public void displayInterstitial() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (adViewInter.isLoaded()) {
					adViewInter.show();
				}
			}
		});

	}

	@Override
	public void menuScreen() {
		RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		adParams.addRule(RelativeLayout.CENTER_IN_PARENT);

		showAd(adParams);

	}

	@Override
	public void gameScreen() {
		/*RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		adParams.addRule(RelativeLayout.CENTER_IN_PARENT);*/

		hideAd();

	}

	@Override
	public void loadoutScreen() {
		hideAd();

	}
}
